<template>
  <div class="manual-import-container">
    <div class="page-header">
      <div class="page-title">手动上传导入</div>
    </div>

    <el-tabs v-model="activeTab" class="import-tabs">
      <el-tab-pane label="文件导入" name="file">
        <el-card class="import-card">
          <div class="upload-area">
            <el-upload
              class="upload-dragger"
              drag
              action="#"
              :auto-upload="false"
              :on-change="handleFileChange"
              :file-list="fileList"
              :limit="5"
              multiple>
              <el-icon class="el-icon--upload"><Upload /></el-icon>
              <div class="el-upload__text">
                拖拽文件到此处或 <em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持XML, JSON, CSV格式的漏洞数据文件，单个文件不超过10MB
                </div>
              </template>
            </el-upload>

            <div class="upload-options">
              <el-form :model="fileImportForm" label-width="80px">
                <el-form-item label="文件格式">
                  <el-radio-group v-model="fileImportForm.format">
                    <el-radio label="xml">XML</el-radio>
                    <el-radio label="json">JSON</el-radio>
                    <el-radio label="csv">CSV</el-radio>
                    <el-radio label="auto">自动检测</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="标准格式">
                  <el-select v-model="fileImportForm.standard" placeholder="选择标准格式" style="width: 100%">
                    <el-option label="CVE" value="cve" />
                    <el-option label="NVD" value="nvd" />
                    <el-option label="CNVD" value="cnvd" />
                    <el-option label="自定义" value="custom" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="importFiles" :disabled="fileList.length === 0">
                    开始导入
                  </el-button>
                  <el-button @click="cancelFileImport">取消</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="手动录入" name="manual">
        <el-card class="import-card">
          <el-form 
            :model="vulnForm" 
            :rules="vulnRules" 
            ref="vulnFormRef" 
            label-width="100px"
            class="vuln-form">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="漏洞编号" prop="vulnId">
                  <el-input v-model="vulnForm.vulnId" placeholder="例如：CVE-2023-1234" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发现日期" prop="discoveryDate">
                  <el-date-picker
                    v-model="vulnForm.discoveryDate"
                    type="date"
                    placeholder="选择发现日期"
                    style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="漏洞名称" prop="name">
              <el-input v-model="vulnForm.name" placeholder="请输入漏洞名称" />
            </el-form-item>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="漏洞类型" prop="type">
                  <el-select v-model="vulnForm.type" placeholder="选择漏洞类型" style="width: 100%">
                    <el-option label="SQL注入" value="sql_injection" />
                    <el-option label="XSS跨站脚本" value="xss" />
                    <el-option label="CSRF跨站请求伪造" value="csrf" />
                    <el-option label="命令执行" value="command_exec" />
                    <el-option label="文件包含" value="file_inclusion" />
                    <el-option label="文件上传" value="file_upload" />
                    <el-option label="权限提升" value="privilege_escalation" />
                    <el-option label="配置错误" value="misconfiguration" />
                    <el-option label="其他" value="other" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="危害等级" prop="severity">
                  <el-select v-model="vulnForm.severity" placeholder="选择危害等级" style="width: 100%">
                    <el-option 
                      v-for="item in severityOptions" 
                      :key="item.value" 
                      :label="item.label" 
                      :value="item.value">
                      <el-tag :type="getSeverityType(item.value)" size="small">{{ item.label }}</el-tag>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="受影响版本" prop="affectedVersions">
              <el-input v-model="vulnForm.affectedVersions" placeholder="例如：Apache Struts 2.0.0-2.5.25" />
            </el-form-item>
            
            <el-form-item label="修复版本" prop="fixedVersions">
              <el-input v-model="vulnForm.fixedVersions" placeholder="例如：Apache Struts 2.5.26 及以上" />
            </el-form-item>
            
            <el-form-item label="漏洞描述" prop="description">
              <el-input 
                v-model="vulnForm.description" 
                type="textarea" 
                :rows="4" 
                placeholder="请详细描述该漏洞的具体情况" />
            </el-form-item>
            
            <el-form-item label="技术细节" prop="technicalDetails">
              <el-input 
                v-model="vulnForm.technicalDetails" 
                type="textarea" 
                :rows="4" 
                placeholder="请输入该漏洞的技术细节，如触发条件、实现原理等" />
            </el-form-item>
            
            <el-form-item label="解决方案" prop="solution">
              <el-input 
                v-model="vulnForm.solution" 
                type="textarea" 
                :rows="4" 
                placeholder="请输入该漏洞的修复方案或缓解措施" />
            </el-form-item>
            
            <el-form-item label="参考链接">
              <div v-for="(link, index) in vulnForm.references" :key="index" class="reference-item">
                <el-input v-model="vulnForm.references[index]" placeholder="参考链接URL">
                  <template #append>
                    <el-button @click="removeReference(index)">删除</el-button>
                  </template>
                </el-input>
              </div>
              <el-button type="primary" link @click="addReference">添加参考链接</el-button>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="submitVulnForm">提交</el-button>
              <el-button @click="resetVulnForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 导入进度对话框 -->
    <el-dialog v-model="importProgressVisible" title="导入进度" width="500px" :close-on-click-modal="false">
      <div class="import-progress">
        <div class="progress-info">正在导入漏洞数据，请勿关闭窗口...</div>
        <el-progress :percentage="importProgress" :stroke-width="18" />
        <div class="progress-detail">
          已导入 {{ importedCount }} 条，错误 {{ errorCount }} 条
        </div>
        <div class="progress-files">
          <div v-for="(file, index) in importingFiles" :key="index" class="file-item">
            <el-icon :class="{ 'is-success': file.status === 'success', 'is-error': file.status === 'error' }">
              <component :is="getFileStatusIcon(file.status)" />
            </el-icon>
            <span>{{ file.name }}</span>
            <span>{{ getFileStatusText(file.status) }}</span>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeImportProgress" :disabled="importProgress < 100 && importProgress > 0">
            {{ importProgress < 100 && importProgress > 0 ? '导入中...' : '关闭' }}
          </el-button>
          <el-button type="primary" @click="viewImportResult" :disabled="importProgress < 100">
            查看结果
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 导入结果对话框 -->
    <el-dialog v-model="importResultVisible" title="导入结果" width="800px">
      <div class="import-result">
        <div class="result-summary">
          <el-alert
            :title="`成功导入 ${importedCount} 条漏洞信息`"
            type="success"
            :closable="false"
            show-icon />
          
          <el-alert
            v-if="errorCount > 0"
            :title="`导入失败 ${errorCount} 条数据`"
            type="error"
            :closable="false"
            style="margin-top: 10px"
            show-icon />
        </div>
        
        <el-tabs v-model="resultActiveTab">
          <el-tab-pane label="成功" name="success">
            <el-table :data="successList" style="width: 100%">
              <el-table-column prop="id" label="漏洞ID" width="150" />
              <el-table-column prop="name" label="漏洞名称" show-overflow-tooltip />
              <el-table-column prop="type" label="类型" width="120" />
              <el-table-column prop="severity" label="等级" width="80">
                <template #default="{ row }">
                  <el-tag :type="getSeverityType(row.severity)">{{ row.severity }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.status === 'new' ? 'success' : 'info'">
                    {{ row.status === 'new' ? '新增' : '更新' }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          
          <el-tab-pane label="失败" name="error" v-if="errorCount > 0">
            <el-table :data="errorList" style="width: 100%">
              <el-table-column prop="file" label="文件名" width="200" />
              <el-table-column prop="line" label="位置" width="80" />
              <el-table-column prop="reason" label="失败原因" show-overflow-tooltip />
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Upload, Check, Close, CircleCheck, CircleClose, Loading } from '@element-plus/icons-vue'

// 当前激活的标签页
const activeTab = ref('file')
const resultActiveTab = ref('success')

// 文件上传相关
const fileList = ref([])
const fileImportForm = reactive({
  format: 'auto',
  standard: 'cve'
})

// 手动录入表单
const vulnFormRef = ref(null)
const vulnForm = reactive({
  vulnId: '',
  name: '',
  type: '',
  severity: '',
  discoveryDate: '',
  affectedVersions: '',
  fixedVersions: '',
  description: '',
  technicalDetails: '',
  solution: '',
  references: ['']
})

// 表单验证规则
const vulnRules = {
  vulnId: [
    { required: true, message: '请输入漏洞编号', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入漏洞名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择漏洞类型', trigger: 'change' }
  ],
  severity: [
    { required: true, message: '请选择危害等级', trigger: 'change' }
  ],
  discoveryDate: [
    { required: true, message: '请选择发现日期', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入漏洞描述', trigger: 'blur' }
  ]
}

// 危害等级选项
const severityOptions = [
  { value: 'Critical', label: '严重' },
  { value: 'High', label: '高危' },
  { value: 'Medium', label: '中危' },
  { value: 'Low', label: '低危' }
]

// 导入进度相关
const importProgressVisible = ref(false)
const importProgress = ref(0)
const importedCount = ref(0)
const errorCount = ref(0)
const importingFiles = ref([])

// 导入结果相关
const importResultVisible = ref(false)
const successList = ref([])
const errorList = ref([])

// 获取危害等级类型
const getSeverityType = (severity) => {
  const severityMap = {
    'Critical': 'danger',
    'High': 'warning',
    'Medium': '',
    'Low': 'info'
  }
  return severityMap[severity] || ''
}

// 处理文件变化
const handleFileChange = (file, fileList) => {
  fileList.value = fileList
}

// 导入文件
const importFiles = () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请先选择要导入的文件')
    return
  }
  
  // 准备导入进度展示
  importProgressVisible.value = true
  importProgress.value = 0
  importedCount.value = 0
  errorCount.value = 0
  importingFiles.value = fileList.value.map(file => ({
    name: file.name,
    status: 'pending'
  }))
  
  // 模拟导入进度
  let currentProgress = 0
  const totalFiles = fileList.value.length
  let processedFiles = 0
  
  const progressInterval = setInterval(() => {
    currentProgress += Math.random() * 10
    
    if (currentProgress >= 100 || processedFiles >= totalFiles) {
      clearInterval(progressInterval)
      currentProgress = 100
      importProgress.value = 100
      
      // 模拟导入结果
      successList.value = []
      errorList.value = []
      
      let totalImported = 0
      let totalErrors = 0
      
      importingFiles.value.forEach((file, index) => {
        const isSuccess = Math.random() > 0.2
        file.status = isSuccess ? 'success' : 'error'
        
        if (isSuccess) {
          const importCount = Math.floor(Math.random() * 10) + 1
          totalImported += importCount
          
          // 生成假的成功数据
          for (let i = 0; i < importCount; i++) {
            successList.value.push({
              id: `CVE-2023-${Math.floor(Math.random() * 10000)}`,
              name: `从 ${file.name} 导入的漏洞示例 ${i + 1}`,
              type: ['SQL注入', 'XSS跨站脚本', '命令执行', '权限提升'][Math.floor(Math.random() * 4)],
              severity: severityOptions[Math.floor(Math.random() * severityOptions.length)].value,
              status: Math.random() > 0.3 ? 'new' : 'updated'
            })
          }
        } else {
          const errorCount = Math.floor(Math.random() * 3) + 1
          totalErrors += errorCount
          
          // 生成假的错误数据
          for (let i = 0; i < errorCount; i++) {
            errorList.value.push({
              file: file.name,
              line: Math.floor(Math.random() * 100) + 1,
              reason: [
                '格式错误，无法解析XML',
                '缺少必要字段：描述',
                '日期格式无效',
                'CVE编号不符合规范'
              ][Math.floor(Math.random() * 4)]
            })
          }
        }
      })
      
      importedCount.value = totalImported
      errorCount.value = totalErrors
      
    } else {
      importProgress.value = Math.floor(currentProgress)
      
      // 模拟文件处理状态更新
      if (Math.random() > 0.7 && processedFiles < totalFiles) {
        importingFiles.value[processedFiles].status = Math.random() > 0.2 ? 'success' : 'error'
        processedFiles++
      }
    }
  }, 500)
}

// 取消文件导入
const cancelFileImport = () => {
  fileList.value = []
}

// 关闭导入进度对话框
const closeImportProgress = () => {
  if (importProgress.value < 100 && importProgress.value > 0) {
    return
  }
  importProgressVisible.value = false
}

// 查看导入结果
const viewImportResult = () => {
  importProgressVisible.value = false
  importResultVisible.value = true
}

// 获取文件状态图标
const getFileStatusIcon = (status) => {
  const statusIconMap = {
    'pending': Loading,
    'success': CircleCheck,
    'error': CircleClose
  }
  return statusIconMap[status] || Loading
}

// 获取文件状态文本
const getFileStatusText = (status) => {
  const statusTextMap = {
    'pending': '等待处理',
    'success': '导入成功',
    'error': '导入失败'
  }
  return statusTextMap[status] || '未知状态'
}

// 添加参考链接
const addReference = () => {
  vulnForm.references.push('')
}

// 移除参考链接
const removeReference = (index) => {
  vulnForm.references.splice(index, 1)
}

// 提交手动录入表单
const submitVulnForm = () => {
  vulnFormRef.value.validate((valid) => {
    if (valid) {
      // 模拟提交
      ElMessage.success('漏洞信息提交成功')
      resetVulnForm()
    } else {
      ElMessage.error('请完善表单信息')
    }
  })
}

// 重置手动录入表单
const resetVulnForm = () => {
  vulnFormRef.value.resetFields()
  vulnForm.references = ['']
}
</script>

<style lang="scss" scoped>
.manual-import-container {
  padding: 20px;
  
  .page-header {
    margin-bottom: 20px;
    
    .page-title {
      font-size: 20px;
      font-weight: bold;
      color: var(--text-color);
    }
  }
  
  .import-tabs {
    background-color: var(--card-bg);
    border-radius: 4px;
    
    :deep(.el-tabs__header) {
      background-color: var(--card-bg);
      
      .el-tabs__item {
        color: var(--text-color-secondary);
        
        &.is-active {
          color: var(--primary-color);
        }
        
        &:hover {
          color: var(--primary-color);
        }
      }
      
      .el-tabs__active-bar {
        background-color: var(--primary-color);
      }
    }
    
    .import-card {
      margin-top: 20px;
      
      .upload-area {
        display: flex;
        gap: 20px;
        
        .upload-dragger {
          flex: 1;
          
          :deep(.el-upload-dragger) {
            background-color: var(--bg-color-secondary);
            border-color: var(--border-color);
            
            &:hover {
              border-color: var(--primary-color);
            }
            
            .el-icon {
              color: var(--text-color-secondary);
            }
            
            .el-upload__text {
              color: var(--text-color);
              
              em {
                color: var(--primary-color);
              }
            }
          }
          
          :deep(.el-upload__tip) {
            color: var(--text-color-secondary);
          }
        }
        
        .upload-options {
          width: 300px;
          padding: 0 15px;
        }
      }
      
      .vuln-form {
        max-width: 900px;
        margin: 0 auto;
        
        .reference-item {
          margin-bottom: 10px;
        }
      }
    }
  }
  
  .import-progress {
    .progress-info {
      margin-bottom: 15px;
      color: var(--text-color);
    }
    
    .progress-detail {
      margin: 15px 0;
      text-align: center;
      color: var(--text-color-secondary);
    }
    
    .progress-files {
      margin-top: 20px;
      max-height: 200px;
      overflow-y: auto;
      
      .file-item {
        display: flex;
        align-items: center;
        padding: 8px 0;
        border-bottom: 1px solid var(--border-color-light);
        color: var(--text-color);
        
        .el-icon {
          margin-right: 10px;
          
          &.is-success {
            color: var(--success-color);
          }
          
          &.is-error {
            color: var(--danger-color);
          }
        }
        
        span:first-of-type {
          flex: 1;
        }
        
        span:last-of-type {
          color: var(--text-color-secondary);
          margin-left: 10px;
        }
      }
    }
  }
  
  .result-summary {
    margin-bottom: 20px;
  }
}
</style> 